package com.ckd.flyingtrip.activity;

import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.TextView;

import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.android.volley.AuthFailureError;
import com.android.volley.Request;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.StringRequest;
import com.ckd.flyingtrip.R;
import com.ckd.flyingtrip.adapter.HomePayAdapter;
import com.ckd.flyingtrip.constants.Constants;
import com.ckd.flyingtrip.dialog.PayWayDialog;
import com.ckd.flyingtrip.fragment.HomeFragment;
import com.ckd.flyingtrip.javabean.HomePayBean;
import com.ckd.flyingtrip.javabean.UserInfoBean;
import com.ckd.flyingtrip.utils.BcUtils;
import com.ckd.flyingtrip.utils.DataCheck;
import com.ckd.flyingtrip.utils.Tools;
import com.ckd.flyingtrip.utils.VolleyErrorUtils;
import com.ckd.flyingtrip.widge.SingleVolleyRequestQueue;
import com.google.gson.Gson;

import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;

public class HomePayActivity extends BaseActivity {

    @BindView(R.id.activity_home_pay_recyclerView)
    RecyclerView recyclerView;
    @BindView(R.id.toolber_color_title)
    TextView title;

    private List<HomePayBean.DataBean> dataBeans = new ArrayList<>();
    private HomePayAdapter adapter;

    private PayWayDialog.Builder pb;

    private int userBindingNum = 0;
    private int cityBatteryMax = 0;
    private String num = "0";
    private boolean b = false;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_home_pay);
        ButterKnife.bind(this);
        title.setText("缴费套餐");

        initView();
        initData();
        initListener();
    }

    private void initListener() {
        adapter.setOnItemClickListener(new HomePayAdapter.OnItemClickListener() {
            @Override
            public void onClick(View view, int position, TextView textView) {
                num = textView.getText().toString();
                switch (dataBeans.get(position).getCostType()) {
                    case "1":
                        b = true;
                        break;
                    case "2":
                        b = false;
                        break;
                }
                if (b) {
                    if (cityBatteryMax - userBindingNum < Integer.parseInt(num)) {
                        toast("租电池数量不能大于本城市的最大租电池数！");
                        return;
                    }
                }
                pb = new PayWayDialog.Builder(HomePayActivity.this,
                        new PayWayDialog.Builder.PriorityListener() {
                            @Override
                            public void refreshPriorityUI(String f) {
                                volleyQueryFei(dataBeans.get(position).getCostId(), f);
                                pb.create().dismiss();
                            }
                        });
                pb.create().show();
            }

            @Override
            public void onAddClick(View view, int position, TextView textView, TextView textView1) {
                int nunber = Integer.parseInt(textView.getText().toString());
                if (cityBatteryMax - userBindingNum > nunber)
                    nunber++;
                else {
                    toast("租电池数量不能大于本城市的最大租电池数！");
                    return;
                }
                textView.setText(nunber + "");
                Double aDouble = Double.parseDouble(dataBeans.get(position).getCostMoney()) * nunber;
                textView1.setText("费 用 金 额 ：¥" + aDouble);
            }

            @Override
            public void onLessClick(View view, int position, TextView textView, TextView textView1) {
                int nunber = Integer.parseInt(textView.getText().toString());
                if (nunber == 1)
                    return;
                nunber--;
                textView.setText(nunber + "");
                Double aDouble = Double.parseDouble(dataBeans.get(position).getCostMoney()) * nunber;
                textView1.setText("费 用 金 额 ：¥" + aDouble);
            }
        });
    }


    private void volleyQueryFei(String id, String type) {
        if (type.equals("weixin")) {
//            Weixin weixin = new Weixin(GoumaiActivity.this, "");
//            weixin.volleyDINGDAN(id);
            dismisProgressDialog();
        } else if (type.equals("alipay")) {
            createLoadingDialog(this, "正在支付中...", true);
            Alipay alipay = new Alipay(HomePayActivity.this, "");
            alipay.volleyQueryJiaofei(id, num, b);
        }
    }

    @Override
    protected void onResume() {
        super.onResume();
        volleyUserInfo();
    }

    private void initData() {
        StringRequest request = new StringRequest(Request.Method.POST, Constants.getmeallist, new Response.Listener<String>() {
            @Override
            public void onResponse(String s) {
                Log.i("缴费套餐", s);
                try {
                    JSONObject json = new JSONObject(s);
                    String code = json.getString("code");
                    String msg = json.getString("msg");
                    if (code.equals("1")) {
                        HomePayBean bean = new Gson().fromJson(s, HomePayBean.class);
                        dataBeans.addAll(bean.getData());
                        if (adapter != null)
                            adapter.notifyDataSetChanged();
                        if (dataBeans.size() == 0)
                            toast("暂无数据！");
                    } else
                        toast(msg);
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        }, new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError volleyError) {
                Log.e("缴费套餐", "" + volleyError);
            }
        }) {
            @Override
            protected Map<String, String> getParams() throws AuthFailureError {

                HashMap<String, String> map = new HashMap<String, String>();
                JSONObject json_url = new JSONObject();
                try {
                    json_url.put("userId", BcUtils.getUid());
                    json_url.put("userArea", Constants.CITYID);
                    json_url.put("userChannel", BcUtils.getUserInfo().getUserChannel());
                } catch (JSONException e) {
                    e.printStackTrace();
                }
                map.put("inputParameter", DataCheck.signCheck(json_url.toString()));

                return map;
            }
        };
        SingleVolleyRequestQueue.getInstance(this).addToRequestQueue(request);
    }

    private void volleyUserInfo() {
        StringRequest request = new StringRequest(Request.Method.POST, Constants.QINGQIUGERENXINXI, new Response.Listener<String>() {
            @Override
            public void onResponse(String s) {
                dismisProgressDialog();
                Log.i("用户信息", s);
                try {
                    JSONObject json = new JSONObject(s);
                    String code = json.getString("code");
                    String msg = json.getString("msg");
                    switch (code) {
                        case "0":
                            toast(msg);
                            break;
                        case "1":
                            JSONObject dataInfo = json.getJSONObject("data");
                            String data = json.getString("data");
                            UserInfoBean userInfoBean = new Gson().fromJson(data, UserInfoBean.class);
                            userBindingNum = Integer.parseInt(userInfoBean.getUserBindingNum());
                            BcUtils.setUserInfo(userInfoBean);
                            BcUtils.setUid(userInfoBean.getUserId());
                            BcUtils.setToken(userInfoBean.getToken());
                            BcUtils.setPhone(userInfoBean.getUserPhone());
                            BcUtils.setSignState(userInfoBean.getUserState());
                            BcUtils.setuserRent(userInfoBean.getUserRent());
                            BcUtils.setuserDeposit(userInfoBean.getUserDeposit());
                            BcUtils.setbindingElectricBicycle(userInfoBean.getBindingElectricBicycle());
                            HomeFragment.userStart = Integer.parseInt(userInfoBean.getUserState());
                            break;
                        case "2":
                            startActivity(new Intent(HomePayActivity.this, UserLogInActivity.class));
                            Tools.closeLogIN(HomePayActivity.this);
                            finish();
                            break;
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                    dismisProgressDialog();
                }
            }
        }, new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError volleyError) {
                dismisProgressDialog();
                VolleyErrorUtils.checkError(volleyError);
            }
        }) {
            @Override
            protected Map<String, String> getParams() throws AuthFailureError {
                HashMap<String, String> map = new HashMap<String, String>();
                JSONObject json_url = new JSONObject();
                try {
                    json_url.put("userId", BcUtils.getUid());
                    json_url.put("userPhone", BcUtils.getUserInfo().getUserPhone());
                    json_url.put("token", BcUtils.getToken());
                } catch (JSONException e) {
                    e.printStackTrace();
                }
                map.put("inputParameter", DataCheck.signCheck(json_url.toString()));
                return map;
            }
        };
        SingleVolleyRequestQueue.getInstance(this).addToRequestQueue(request);
    }

    private void initView() {
        cityBatteryMax = Integer.parseInt(BcUtils.getCityBatteryMax());

        recyclerView.setLayoutManager(new LinearLayoutManager(this));
        adapter = new HomePayAdapter(this, dataBeans);
        recyclerView.setAdapter(adapter);
    }

    @OnClick(R.id.toolber_color_back)
    public void onViewClicked() {
        finish();
    }
}
